use loco_rs::prelude::*;
use sea_orm::sea_query::ExprTrait;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::jobs::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub queue: String,
    pub payload: String,
    pub attempts: u8,
    pub reserved_at: Option<u32>,
    pub available_at: u32,
    pub created_at: u32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {
    #[validate(length(min = 1, message = "Queue must not be empty."))]
    pub queue: String,
}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {
            queue: self.queue.as_ref().to_owned(),
        })
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for super::_entities::jobs::ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds a job by the provided id
    ///
    /// # Errors
    ///
    /// When could not find job or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let job = jobs::Entity::find()
            .filter(model::query::condition().eq(jobs::Column::Id, id).build())
            .one(db)
            .await?;
        job.ok_or_else(|| ModelError::EntityNotFound)
    }

    /// finds jobs by the provided queue
    ///
    /// # Errors
    ///
    /// When could not find jobs or DB query error
    pub async fn find_by_queue(db: &DatabaseConnection, queue: &str) -> ModelResult<Vec<Self>> {
        let jobs = jobs::Entity::find()
            .filter(
                model::query::condition()
                    .eq(jobs::Column::Queue, queue)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(jobs)
    }

    /// finds available jobs
    ///
    /// # Errors
    ///
    /// When could not find jobs or DB query error
    pub async fn find_available(db: &DatabaseConnection) -> ModelResult<Vec<Self>> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as u32;

        let jobs = jobs::Entity::find()
            .filter(
                model::query::condition()
                    .is_null(jobs::Column::ReservedAt)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(jobs)
    }

    /// Asynchronously creates a job and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the job into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let job = jobs::ActiveModel {
            queue: ActiveValue::set(params.queue.to_string()),
            payload: ActiveValue::set(params.payload.to_string()),
            attempts: ActiveValue::set(params.attempts),
            reserved_at: ActiveValue::set(params.reserved_at),
            available_at: ActiveValue::set(params.available_at),
            created_at: ActiveValue::set(params.created_at),
            ..Default::default()
        }
        .insert(db)
        .await?;

        Ok(job)
    }
}

impl ActiveModel {
    /// Updates the job's attempts count
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_attempts(
        mut self,
        db: &DatabaseConnection,
        attempts: u8,
    ) -> ModelResult<Model> {
        self.attempts = ActiveValue::set(attempts);
        Ok(self.update(db).await?)
    }

    /// Updates the job's reservation status
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_reservation(
        mut self,
        db: &DatabaseConnection,
        reserved_at: Option<u32>,
    ) -> ModelResult<Model> {
        self.reserved_at = ActiveValue::set(reserved_at);
        Ok(self.update(db).await?)
    }

    /// Updates the job's availability
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_availability(
        mut self,
        db: &DatabaseConnection,
        available_at: u32,
    ) -> ModelResult<Model> {
        self.available_at = ActiveValue::set(available_at);
        Ok(self.update(db).await?)
    }
}
